#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509.h>

// #define BUFFER_SIZE 4096 * 10
#define BUFFER_SIZE 1024000
#define HTTPS_PORT 443

void handle_https(int client_socket) {
    // 创建 SSL 上下文
    SSL_CTX *ssl_ctx = SSL_CTX_new(SSLv23_server_method());
    if (!ssl_ctx) {
        perror("Error creating SSL context");
        return;
    }

    // 选择SSL版本
    // SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);
    // SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_1_VERSION);
    // SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION);


    // 加载服务器证书
    // if (SSL_CTX_use_certificate_file(ssl_ctx, "./cert/server.crt", SSL_FILETYPE_PEM) <= 0) {
    //     ERR_print_errors_fp(stderr);
    //     SSL_CTX_free(ssl_ctx);
    //     exit(EXIT_FAILURE);
    // }

    // 加载服务器私钥
    // if (SSL_CTX_use_PrivateKey_file(ssl_ctx, "./cert/server.key", SSL_FILETYPE_PEM) <= 0) {
    // if (SSL_CTX_use_PrivateKey_file(ssl_ctx, "./cert/private.key", SSL_FILETYPE_PEM) <= 0) {
    //     ERR_print_errors_fp(stderr);
    //     SSL_CTX_free(ssl_ctx);
    //     exit(EXIT_FAILURE);
    // }

    // 检查私钥是否和证书匹配
    // if (!SSL_CTX_check_private_key(ssl_ctx)) {
    //     fprintf(stderr, "Private key does not match the certificate.\n");
    //     SSL_CTX_free(ssl_ctx);
    //     exit(EXIT_FAILURE);
    // }


    // 加载服务器证书和私钥
    if (SSL_CTX_use_certificate_file(ssl_ctx, "./cert/server.crt", SSL_FILETYPE_PEM) <= 0 ||
        SSL_CTX_use_PrivateKey_file(ssl_ctx, "./cert/private.key", SSL_FILETYPE_PEM) <= 0) {
        perror("Error loading certificate or private key");
        SSL_CTX_free(ssl_ctx);
        return;
    }

    // SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);


    // 创建 SSL 结构
    SSL *ssl = SSL_new(ssl_ctx);
    if (!ssl) {
        perror("Error creating SSL structure");
        SSL_CTX_free(ssl_ctx);
        return;
    }

    // 检查证书链长度
    X509* cert = SSL_get_peer_certificate(ssl);
    if (cert != NULL) {
        int chain_length = i2d_X509(cert, NULL);
        printf("Certificate chain length: %d\n", chain_length);

        // 在不再需要 cert 的时候释放它
        X509_free(cert);
    } else {
        // 没有证书
        unsigned long err = ERR_get_error();
        fprintf(stderr, "OpenSSL error: %s\n", ERR_error_string(err, NULL));
        printf("No certificate found.\n");
    }

    // 将 SSL 结构绑定到客户端套接字
    if (SSL_set_fd(ssl, client_socket) == 0) {
        perror("Error setting SSL file descriptor");
        SSL_free(ssl);
        SSL_CTX_free(ssl_ctx);
        return;
    }

    // 进行 SSL 握手
    while (SSL_accept(ssl) <= 0) {
        int state = SSL_get_state(ssl);
        if (state == SSL_ST_CONNECT) {
            // 握手成功
            break;
        } else if (state == SSL_ST_ACCEPT) {
            // 继续握手
            continue;
        } else {
            // 握手失败
            perror("Error during SSL handshake");
            unsigned long err = ERR_get_error();
            printf("OpenSSL SSL_accept Error: %s\n", ERR_error_string(err, NULL));
            ERR_print_errors_fp(stderr);
            break;
        }
    }

    

    // 进行 SSL 握手
    // if (SSL_accept(ssl) <= 0) {
    //     perror("Error during SSL handshake");
    //     unsigned long err = ERR_get_error();
    //     printf("OpenSSL SSL_accept Error: %s\n", ERR_error_string(err, NULL));
    //     SSL_free(ssl);
    //     SSL_CTX_free(ssl_ctx);
    //     return;
    // }

    // int state = SSL_get_state(ssl);
    // if( state <= 0){
    //     unsigned long err = ERR_get_error();
    //     printf("SSL_get_state returned %d. OpenSSL error: %s\n", state, ERR_error_string(err, NULL));
    // }

    // SSL 握手完成，可以进行数据传输了
    char buffer[BUFFER_SIZE];
    ssize_t bytes_received, bytes_sent;

    // 读取加密的数据
    bytes_received = SSL_read(ssl, buffer, sizeof(buffer));
    if (bytes_received <= 0) {
        perror("Error receiving encrypted data");
    } else {
        // 在这里可以对加密数据进行处理

        // 发送解密后的数据
        bytes_sent = SSL_write(ssl, buffer, bytes_received);
        if (bytes_sent < bytes_received) {
            perror("Error sending decrypted data");
        }
    }

    // 关闭 SSL 结构
    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ssl_ctx);
}

int start_proxy(int port) {
    // 初始化 OpenSSL 库
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    SSL_load_error_strings();
    
    // 创建服务器套接字
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len = sizeof(client_addr);

    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        perror("Error creating server socket");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(8888);

    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("Error binding server socket");
        exit(EXIT_FAILURE);
    }

    if (listen(server_socket, 10) == -1) {
        perror("Error listening for connections");
        exit(EXIT_FAILURE);
    }

    printf("Proxy server is running on port 8888...\n");

    while (1) {
        // 接受连接
        printf("Start accepting connection 11 %u \n", client_addr_len);
        client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
        printf("Start accepting connection 22 %d \n", client_socket);
        if (client_socket < 0) {
            perror("Error accepting connection");
            continue;
        }

        // 处理直接连接
        printf("Start For handle_connection ... \n");
        if (fork() == 0) {
            close(server_socket);
            
            // 处理 HTTPS 请求
            handle_https(client_socket);

            close(client_socket);
            exit(EXIT_SUCCESS);
        } else {
            close(client_socket);
        }
    }

     // 关闭服务器套接字
    close(server_socket);
    ERR_free_strings();
    EVP_cleanup();

    return 0;
}
